package com.appistry.api.rest.impl;

import java.net.InetAddress;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import com.appistry.api.rest.domain.Credentials;
import com.appistry.api.rest.domain.ssl.EasySSLProtocolSocketFactory;

public class HttpsRestConnection extends AbstractRestConnection {
	private static final String PROTOCOL = "https";
	private static final int DEFAULT_PORT = 443;
	private HostConfiguration hostConfiguration = new HostConfiguration();
	private UsernamePasswordCredentials usernamePasswordCredentials;
	
	public HttpsRestConnection(InetAddress address, int port, Credentials credentials) {				
		super();
		
		//For now accept self signed certs
		Protocol protocol = new Protocol(PROTOCOL, (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), port);
		hostConfiguration.setHost(address.getHostAddress(), port, protocol);	
		hostConfiguration.setParams(getHostParams());
		
		//set credentials and preemptive auth				
		if(credentials!=null){
			this.usernamePasswordCredentials = new UsernamePasswordCredentials(credentials.getUser(), credentials.getPassword());
			getHttpClientParams().setAuthenticationPreemptive(true);
		}
	}

	public HttpsRestConnection(InetAddress address, Credentials credentials) {
		this(address, DEFAULT_PORT, credentials);
	}

	public HttpsRestConnection(InetAddress address, int port) {
		this(address, port, null);
	}

	public HttpsRestConnection(InetAddress address) {
		this(address, DEFAULT_PORT, null);
	}

	protected HostConfiguration getHostConfiguration() {
		return hostConfiguration;
	}

	protected void setHostConfiguration(HostConfiguration hostConfiguration) {
		this.hostConfiguration = hostConfiguration;
	}

	protected UsernamePasswordCredentials getUsernamePasswordCredentials() {
		return usernamePasswordCredentials;
	}

	protected void setUsernamePasswordCredentials(UsernamePasswordCredentials credentials) {
		this.usernamePasswordCredentials = credentials;
	}



}
